<template>
	<a-row style="height: 98%">
		<a-col :span="24">
			<tiny-split v-model="config.split">
				<template #left>
					<a-card
						:bodyStyle="{ paddingRight: '0', paddingBottom: '0', paddingLeft: '0' }"
						:borderd="false"
						style="height: 100%; overflow: scroll"
					>
						<a-tree
							class="tree"
							ref="tree"
							node-key="id"
							v-model:expandedKeys="config.expandedKeys"
							style="height: 100%; overflow: scroll"
							:tree-data="config.treeData"
							:blockNode="true"
							:load-data="loadTreeData"
							@expand="treeExpend"
							:field-names="defaultProps"
							@select="handleNodeClick"
						>
							<template #title="data">
								<a-dropdown :trigger="['contextmenu']">
									<span style="width: 100%; overflow-x: scroll; white-space: nowrap">
										<svg
											v-if="data.type == 'group'"
											t="1728180540496"
											class="icon"
											viewBox="0 0 1024 1024"
											version="1.1"
											xmlns="http://www.w3.org/2000/svg"
											p-id="4296"
											width="15"
											height="15"
										>
											<path
												d="M369.152 547.84H225.28a128 128 0 0 0-128 128v61.44a128 128 0 0 0 128 128h143.872a128 128 0 0 0 128-128v-61.44a128 128 0 0 0-128-128z m76.8 189.44a76.8 76.8 0 0 1-76.8 76.8H225.28a76.8 76.8 0 0 1-76.8-76.8v-61.44a76.8 76.8 0 0 1 76.8-76.8h143.872a76.8 76.8 0 0 1 76.8 76.8zM798.72 547.84h-143.872a128 128 0 0 0-128 128v61.44a128 128 0 0 0 128 128h143.872a128 128 0 0 0 128-128v-61.44a128 128 0 0 0-128-128z m76.8 189.44a76.8 76.8 0 0 1-76.8 76.8h-143.872a76.8 76.8 0 0 1-76.8-76.8v-61.44a76.8 76.8 0 0 1 76.8-76.8h143.872a76.8 76.8 0 0 1 76.8 76.8zM369.152 188.928H225.28a128 128 0 0 0-128 128v61.44a128 128 0 0 0 128 128h143.872a128 128 0 0 0 128-128v-61.44a128 128 0 0 0-128-128z m76.8 189.44a76.8 76.8 0 0 1-76.8 76.8H225.28a76.8 76.8 0 0 1-76.8-76.8v-61.44a76.8 76.8 0 0 1 76.8-76.8h143.872a76.8 76.8 0 0 1 76.8 76.8zM798.72 188.928h-143.872a128 128 0 0 0-128 128v61.44a128 128 0 0 0 128 128h143.872a128 128 0 0 0 128-128v-61.44a128 128 0 0 0-128-128z m76.8 189.44a76.8 76.8 0 0 1-76.8 76.8h-143.872a76.8 76.8 0 0 1-76.8-76.8v-61.44a76.8 76.8 0 0 1 76.8-76.8h143.872a76.8 76.8 0 0 1 76.8 76.8z"
												fill="#1afa29"
												p-id="4297"
											></path>
										</svg>

										<template v-for="item in componentConfig">
											<a-avatar
												:src="'data:image/svg+xml;base64,' + btoa(item.icon)"
												size="small"
												v-if="data.type == item.type"
											/>
										</template>

										&nbsp;<span>{{ data.name }}</span>
									</span>
									<template #overlay>
										<a-menu @click="({ key: menuKey }) => onContextMenuClick(data, menuKey)">
											<a-menu-item key="add" v-if="data.type === 'group'"> 新增 </a-menu-item>
											<template v-for="it in componentConfig">
												<template v-for="item in it.menuItem">
													<a-menu-item :key="item.key" v-if="item.show(data)">
														{{ typeof item.text === 'function' ? item.text(data) : item.text }}
													</a-menu-item>
												</template>
											</template>
											<a-menu-item key="edit" v-if="data.id != '0'">修改</a-menu-item>
											<a-menu-item key="remove" v-if="data.id != '0'">删除</a-menu-item>
										</a-menu>
									</template>
								</a-dropdown>
							</template>
						</a-tree>
					</a-card>
				</template>
				<template #right>
					<a-card :borderd="false" style="height: 100%">
						<a-tabs
							v-model:activeKey="config.flowKey"
							type="editable-card"
							hide-add
							style="height: 100%"
							@edit="onTabRemove"
						>
							<a-tab-pane
								v-for="processTab in config.flowTabList"
								:key="processTab.id"
								style="height: 100%; overflow-y: scroll"
								:tab="processTab.name + '@' + processTab.version"
							>
								<template v-for="item in componentConfig">
									<component
										:is="item.tabView"
										v-if="processTab.type === item.type"
										:officeId="processTab.id"
										:id="processTab.id"
									></component>
								</template>
							</a-tab-pane>
						</a-tabs>
					</a-card>
				</template>
			</tiny-split>
		</a-col>
		<!--		<a-col :span="18">-->
		<!--			-->
		<!--		</a-col>-->
		<Group
			v-if="config.productId"
			:hiddenFlag="true"
			ref="groupRef"
			relationTypeCode="SCENE"
			:productId="config.productId"
			:operaCallback="reloadTreeData"
		></Group>

		<template v-for="item in componentConfig">
			<component
				:is="item.operatorView"
				v-if="config.productId"
				:operaCallback="reloadTreeData"
				:productId="config.productId"
				:hiddenFlag="true"
				:ref="item.type + 'Ref'"
			></component>
		</template>
	</a-row>
</template>

<script setup>
	import { getCurrentInstance, h, onMounted, ref, watch } from 'vue'
	import groupApi from '@/api/group/groupApi'
	import Group from '@/components/Group/index.vue'

	import { config as componentConfig, loadData } from '@/views/process/ideComponentConfig.js'

	const btoa = (t) => {
		return window.btoa(t)
	}

	const groupRef = ref()
	const tree = ref()
	const { proxy } = getCurrentInstance()
	//组装树

	let props = defineProps([])
	let config = ref({
		productId: null,
		treeData: [],
		flowTabList: [],
		split: 0.2,
		parentTreeNode: null,
		groupId: null,
		expandedKeys: [],
		flowKey: null
	})

	const defaultProps = ref({
		children: 'children',
		title: 'name'
	})

	const treeExpend = (d, b, c) => {
		b.node.loaded = false
	}

	onMounted(() => {
		config.value.productId = proxy.$route.query.id
		buildTree()
	})

	//加载分组。
	const handleNodeClick = (key, { node: { dataRef } }) => {
		let comp = componentConfig.find((v) => v.type == dataRef.type)
		if (comp) {
			if (comp.tabView == null) {
				return
			}
		}

		let find = config.value.flowTabList.find((v) => {
			return v.id == dataRef.id
		})
		if (find) {
			config.value.flowKey = find.id
		} else {
			if (dataRef.type == 'group') {
				return
			}
			let name = 'name'
			if (comp) {
				name = comp.dataMainName
			}
			config.value.flowTabList.push({
				type: dataRef.type,
				id: dataRef.id,
				name: dataRef.processName || dataRef[name],
				version: dataRef.processVersion || ''
			})
			config.value.flowKey = dataRef.id
		}
	}

	const buildTree = async () => {
		//构造整棵树
		config.value.treeData = []
		// config.value.expandedKeys = []
		//先查询分组
		let groupTree = await queryGroupTree()
		treeNodeSetType(groupTree, 'group', 'groupName')
		//动态查询的
		config.value.treeData = groupTree
	}

	const findNodeInfo = (id, data) => {
		let result = null
		if (!data || data.length <= 0) {
			return result
		}
		for (let i = 0; i < data.length; i++) {
			let d = data[i]

			if (!d) {
				continue
			}
			if (d.id == id) {
				result = {
					node: d,
					index: i,
					parent: data
				}
				break
			}
			let childrenList = d.children
			if (childrenList && childrenList.length > 0) {
				let tempNode = findNodeInfo(id, childrenList)
				if (tempNode) {
					result = tempNode
					break
				}
			}
		}
		return result
	}

	const reloadTreeData = (action, type, data) => {
		//找到parent重新loading
		if (action == 'add') {
			data.type = type
			let comp = componentConfig.find((v) => v.type === data.type)
			if (comp) {
				data.isLeaf = comp.isLeafFlag
			}
			data.name = getName(type, data)
			if (!config.value.parentTreeNode.children) {
				config.value.parentTreeNode.children = []
			}
			config.value.parentTreeNode.children.push({
				...data
			})
		} else if (action == 'offline') {
			let nodeInfo = findNodeInfo(data.id, config.value.treeData)
			for (let c in data) {
				nodeInfo.node[c] = data[c]
			}
			//
		} else if (action == 'edit') {
			let nodeInfo = findNodeInfo(data.id, config.value.treeData)
			nodeInfo.node.name = getName(type, data)
		} else if (action == 'delete') {
			let nodeInfo = findNodeInfo(data.id, config.value.treeData)
			delete nodeInfo.parent[nodeInfo.index]
			onTabRemove(nodeInfo.node.id, 'remove')
		}
	}

	const findCompByMenuKey = (menuKey) => {
		let c = componentConfig.filter((v) => {
			let f = v.menuItem.filter((vv) => {
				return vv.key === menuKey
			})
			// if (f != null && f.length > 1) {
			// 	return null;
			// }
			return f != null && f.length > 0
		})

		if (c != null && c.length > 1) {
			return null
		}
		return c[0]
	}
	const onContextMenuClick = (data, menuKey) => {
		config.value.parentTreeNode = data
		let comp = findCompByMenuKey(menuKey)
		if (!comp) {
			comp = componentConfig.find((v) => v.type === data.type)
		}
		let cloneData = { ...data }
		delete cloneData.dataRef
		delete cloneData.data

		let b = null
		if (comp) {
			b = JSON.parse(JSON.stringify(comp))
		}
		if(!b){
			b={}
		}
		if(!b.menuItem){
				b.menuItem = [];
		}
		let find = b.menuItem.find((v) => v.key == menuKey)

		if (find && find.type) {
			b.type = find.type
		}

		if (comp != null) {
			proxy.$refs[b.type + 'Ref'][0].show(menuKey.toLowerCase().replace(b.type.toLowerCase(), ''), cloneData)
			return
		}

		//新增
		if (cloneData.type === 'group') {
			if (menuKey === 'add') {
				groupRef.value.show('add', {
					id: cloneData.id
				})
			} else if (menuKey === 'edit') {
				groupRef.value.show('edit', cloneData)
			} else if (menuKey === 'remove') {
				alert(cloneData.id)
				groupRef.value.show('delete', {
					id: cloneData.id
				})
			}
		} else {
			comp = componentConfig.find((v) => v.type === cloneData.type)
			if (comp != null) {
				if (menuKey === 'edit') {
					proxy.$refs[comp.type + 'Ref'][0].show('edit', cloneData)
				} else if (menuKey === 'remove') {
					proxy.$refs[comp.type + 'Ref'][0].show('delete', cloneData)
				}
			}
		}
	}

	const queryGroupTree = async () => {
		const d = await groupApi.queryGroupTree({
			relationTypeCode: 'SCENE',
			productId: config.value.productId
		})
		return d
	}

	const onTabRemove = (tabKey, action) => {
		if (action === 'remove') {
			// const tag = config.value.flowTabList.find((tag) => tag.id === tabKey)

			const tabs = config.value.flowTabList
			let activeName = config.value.flowKey
			if (activeName === tabKey) {
				tabs.forEach((tab, index) => {
					if (tab.id === tabKey) {
						const nextTab = tabs[index + 1] || tabs[index - 1]
						if (nextTab) {
							activeName = nextTab.id
						}
					}
				})
			}
			config.value.flowKey = activeName
			config.value.flowTabList = tabs.filter((tab) => tab.id !== tabKey)
		}
	}

	const treeNodeSetType = (trees, type, name) => {
		if (!trees || trees.length <= 0) {
			return
		}
		for (let tree of trees) {
			if (tree.typeFlag == true) {
				type = tree.type
				let comp = componentConfig.find((v) => v.type == type)
				name = comp.dataMainName
			}
			tree.type = type
			tree.isLeaf = false
			if (tree[name]) {
				tree.name = tree[name]
			}

			if (tree.children) {
				treeNodeSetType(tree.children, type)
			}
		}
	}
	//productId

	const loadTreeData = (treeNode) => {
		//console.log(treeNode)
		return new Promise(async (resolve) => {
			// if (treeNode.dataRef.children) {
			// 	resolve();
			// 	return;
			// }
			let groupChildren = []
			if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
				groupChildren = treeNode.dataRef.children.filter((v) => v.type == 'group')
			}

			let type = treeNode.dataRef.type
			if (type == 'group' && treeNode.dataRef.id != 0) {
				// let data = await queryProcessList(treeNode.dataRef.id);
				// treeNodeSetType(data, "process", "processName")
				// if (!data) {
				// 	data = []
				// }
				let result = []

				let b = await loadData(treeNode.dataRef.id, config.value.productId)
				if (!b) {
					b = []
				}
				let fv = []
				for (let tb of b) {
					fv.push({
						...tb.data,
						type: tb.type,
						typeFlag: true
					})
				}
				b = fv
				treeNodeSetType(b, null, null)
				setIsLeafFlag(b, null)

				result.push(...b)

				// for (let comp of componentConfig) {
				// 	if (comp.loadData) {
				// 		let b = await comp.loadData(treeNode.dataRef.id, config.value.productId)
				// 		treeNodeSetType(b, comp.type, comp.dataMainName)
				// 		setIsLeafFlag(b, comp.isLeafFlag)
				// 		if (!b) {
				// 			b = []
				// 		}
				// 		result.push(...b)
				// 	}
				// }
				if (groupChildren == null) {
					groupChildren = []
				}
				let data = [...groupChildren, ...result]
				treeNode.dataRef.children = data
				config.value.treeData = [...config.value.treeData]
			} else {
				let comp = componentConfig.find((v) => v.type == type)
				if (!comp) {
					comp = {}
				}
				let childComp = componentConfig.find((v) => v.type == comp.childType)

				if (childComp) {
					if (childComp.loadData) {
						//查询流程版本列表
						let data = await childComp.loadData(treeNode.dataRef.id)
						treeNodeSetType(data, childComp.type, childComp.dataMainName)
						setIsLeafFlag(data, childComp.isLeafFlag)
						if (!data) {
							data = []
						}
						treeNode.dataRef.children = data
						config.value.treeData = [...config.value.treeData]
					}
				}
			}
			resolve()
		})
	}
	const getName = (type, data) => {
		let comp = componentConfig.find((v) => v.type == type)
		let name = null
		if (type == 'group') {
			name = data.groupName
		}
		if (comp) {
			name = data[comp.dataMainName]
		}
		return name || data.name
	}
	const setIsLeafFlag = (data, isLeaf) => {
		if (!data || data.length <= 0) {
			return
		}
		for (let tree of data) {
			if (tree.typeFlag == true) {
				let comp = componentConfig.find((v) => v.type == tree.type)
				isLeaf = comp.isLeafFlag
			}
			tree.isLeaf = isLeaf
		}
	}
</script>

<style scoped>
	:deep(.ant-card-body) {
		height: 100% !important;
	}

	:deep(.ant-tabs-content) {
		height: 100% !important;
	}
</style>
